package com.atguigu.eduservice.controller;


import com.atguigu.commonutils.R;
import com.atguigu.eduservice.entity.EduComment;
import com.atguigu.eduservice.entity.EduTeacher;
import com.atguigu.eduservice.entity.vo.CoursePublishVo;
import com.atguigu.eduservice.service.EduCommentService;
import com.atguigu.eduservice.service.client.UcenterClient;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 评论 前端控制器
 * </p>
 *
 * @author hwt
 * @since 2022-09-27
 */
@RestController
@RequestMapping("/eduservice/educomment")
public class EduCommentController {
    @Resource
    private UcenterClient ucenterClient;

    @Resource
    private EduCommentService commentService;

    // 用户进行评论，comment需要的参数：courseId（课程id）、teacherId（讲师id）、content（评论）
    @PostMapping("/comment")
    public R Comment(HttpServletRequest request, @RequestBody(required = false) EduComment comment) {
        // 从 request 中获取到 token
        String token = request.getHeader("token");

        // 由于用户操作，是在 service-ucenter 模块中，所以我们需要将 service-ucenter 注册到 nacos 中去
        R infoByToken = ucenterClient.getInfoByToken(token);

        if (infoByToken != null && infoByToken.getSuccess()) {
            Map<String, Object> data = infoByToken.getData();
            String memberId = (String) data.get("memberId");
            String avatar = (String) data.get("avatar");
            String nickname = (String) data.get("nickname");
            if (comment == null) return R.error().message("非法参数异常");
            // 设置用户信息
            comment.setMemberId(memberId);
            comment.setAvatar(avatar);
            comment.setNickname(nickname);
            return commentService.save(comment) ? R.ok() : R.error().message("评论失败，请稍后重试");
        }

        return infoByToken;
    }

    // 显示用户评论
    @GetMapping("/showComment/{page}/{limit}/{courseId}")
    public R showComment(@PathVariable("page") long page,
                         @PathVariable("limit") long limit,
                         @PathVariable("courseId") String courseId) {

        // 创建分页对象 current 当前页    limit 每页条数
        Page<EduComment> pageObj = new Page<>(page, limit);

        QueryWrapper<EduComment> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id", courseId);
        wrapper.orderByDesc("gmt_create");

        commentService.page(pageObj,wrapper);

        // 总记录数
        long total = pageObj.getTotal();

        // 当前页的数据
        List<EduComment> records = pageObj.getRecords();

        return R.ok().data("list", records).data("total",total);
    }
}

